<?php
/*
The Knowledge Ferret - Document Explorer
Copyright (C) 2010 David R. Pratten

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/


$dbconn = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD) or die('Could not connect: ' . mysql_error());
$db = mysql_select_db(DB_NAME, $dbconn);

function firstLeaf($results, $result_no) { #return self for leaves, or first leaf for branches
	$i = $result_no;
	do  {
		if ($results[$i]['leaf']) return $i;
		#echo $i.'|'.$result_no.';';
		$i += 1;
	} while ($i < count($results));
	return $result_no;
}

function getRelated($results, $page2result, $permalink) { # returns own related for leaves, or most freqently occuring related items for branches
	$result_no = $page2result[$permalink];
	$page_no = $results[$result_no]['id'];
	if ($results[$result_no]['leaf']) return explode(',',$results[$result_no]["related"]);
	# otherwise accumulate all subordinate related
	$related_list = array();
	foreach ($results as $result) {
		if(in_array($page_no,explode(',',$result['ancestors']))) { #is a sub branch
			$related_list = array_merge($related_list,explode(',',$result['related']));
		}
	}
	#print_r($related_list);
	foreach ($related_list as $r) {
		$rcount[$r] += 1;
	}
	asort($rcount);
	return array_slice(array_keys($rcount),0,NO_OF_RELATED);
}


function filtervar($pattern, $variable) {
	preg_match($pattern, $variable, $in);
	return $in[0];
}

function extractvar($pattern, $variable) {
	preg_match($pattern, $variable, $in);
	return $in;
}


function filterinput($pattern, $variable) {
	preg_match($pattern, $_GET[$variable], $in);
	return $in[0];
}

function extractinput($pattern, $variable) {
	preg_match($pattern, $_GET[$variable], $in);
	return $in;
}

function extractallinput($pattern, $variable) {
	preg_match_all($pattern, $_GET[$variable], $in);
	return $in;
}


function filterpostinput($pattern, $variable) {
	preg_match($pattern, $_POST[$variable], $in);
	return $in[0];
}

function extractpostinput($pattern, $variable) {
	preg_match($pattern, $_POST[$variable], $in);
	return $in;
}



function e($a) {return mysql_escape_string($a);}

function expandquery($sql, $params) {
	return vsprintf($sql, $params);

}

function cachequery($sql, $params=array(), $debug=false, $stoponerror=true) {
$substsql = expandquery($sql, $params);
if ($debug) {
  echo $substsql;
  echo "<br /><br />";
}
$caching = false;
if ($caching) {
	$cacheprefix = '/cache/';
	$cachename =  dirname($_SERVER['SCRIPT_FILENAME']).$cacheprefix.md5($substsql);
	if (file_exists($cachename)) {
		$result = unserialize(file_get_contents($cachename));
		return $result;
	} 
}
$resultraw = mysql_query($substsql);
if (mysql_error()) {
	if ($stoponerror) die("<br />"."<br />".$substsql."<br />".'Query failed: <br /><strong>#' . mysql_error().'</strong>, ');
	return false;
}




$result = array();
if ($resultraw and substr(strtolower(trim($substsql)),0,6)=="select") {
	while ($theresult = mysql_fetch_array($resultraw, MYSQL_ASSOC)) {
		$result[] = $theresult;
	}
}
if ($caching) file_put_contents($cachename, serialize($result));
return $result;
}


//OK

//DEBUG
function printtable ($title, $result, $trunc = 0) {
	$html .= "<h1>".$title."</h1><table border=1>";
	$first =  true;
	foreach ($result as $line) {
		if ($first) {
			$first = false;
			$html .= '<tr>';
			foreach ($line as $col=>$val) {
				$html .= '<td><strong>'.$col.'</strong></td>';
			}
			$html .= '</tr>';
		}
		$html .= '<tr>';
		if (is_array($line)) {
			foreach ($line as $col=>$val) {
				if ($trunc>0) $printval = substr($val,0,$trunc); else $printval = $val;
				$html .= '<td>'.$printval.'</td>';
			}
		}
		$html .= '</tr>';
	}
	$html .= "</table>";
	return $html;
}

	function RGB_to_HSV ( $rgbx ) // 3 2-digit hex numbers as as string
    {
        $rgb = str_split($rgbx,2);
		$r = hexdec($rgb[0])/255;
        $g = hexdec($rgb[1])/255;
        $b = hexdec($rgb[2])/255;
        
        $MAX = max($r,$g,$b);
        $MIN = min($r,$g,$b);
        
        if     ($MAX == $MIN) return array(0,0,$MAX);
        if     ($r == $MAX) $HUE = ((0 + (($g - $b)/($MAX-$MIN))) * 60);
        elseif ($g == $MAX) $HUE = ((2 + (($b - $r)/($MAX-$MIN))) * 60);
        elseif ($b == $MAX) $HUE = ((4 + (($r - $g)/($MAX-$MIN))) * 60);
        if     ( $HUE < 0 ) $HUE += 360;
        
        return array($HUE,(($MAX - $MIN)/$MAX)*100,$MAX*100); //array(0-360,0-100,0-100)
    }
    
    // Code from Mike Snead, "RGB color to Hue/Sat/Brightness Conversion (and back)", 
    // http://www.phpfreaks.com/quickcode/RGB-color-to-HueSatBrightness-Conversion-and-back/537.php
    // [Jon Aquino 2005-11-02]    
	function HSV_to_RGB ( $HSV ) // array(0-360,0-100,0-100)
    {	
		$H = $HSV[0];
		$S = $HSV[1]/100;
		$V = $HSV[2]/100;
        if ($S == 0) return array($V * 255,$V * 255,$V * 255);
    
        $Hi = floor($H/60);
        $f  = (($H/60) - $Hi);
        $p  = ($V * (1 - $S));
        $q  = ($V * (1 - ($S * $f)));
        $t  = ($V * (1 - ($S * (1 - $f))));
    
        switch ( $Hi )
        {
            case 0  : $red = $V; $gre = $t; $blu = $p; break;
            case 1  : $red = $q; $gre = $V; $blu = $p; break;
            case 2  : $red = $p; $gre = $V; $blu = $t; break;
            case 3  : $red = $p; $gre = $q; $blu = $V; break;
            case 4  : $red = $t; $gre = $p; $blu = $V; break;
            case 5  : $red = $V; $gre = $p; $blu = $q; break;
            default : exit("error -- invalid parameters\n\n");
        }
    
        return dechex2(round($red * 255)).dechex2(round($gre * 255)).dechex2(round($blu * 255)); //3 2-digit hex numbers as as string
    }    
    
function dechex2 ($d) {
	$h = dechex($d);
	if (strlen($h)==1) $h = '0'.$h;
	return $h;
}



function unpackarraytosql($a, $str = array(), &$sqlfields = array(), &$sqlvals = array())
{

    foreach ($a as $k => $v) {

        //echo "[$k]".' => ';
				
        if (is_array($v)) {
        		
            unpackarraytosql($v,array_merge($str,array($k)), $sqlfields,$sqlvals);
        }
        else {   
        //       echo implode("_",array_merge($str,array($k)))."<br />";
        if ($v === "TRUE") $v = 1;
        if ($v === "FALSE") $v = 0;
        
				$sqlfields[] = implode("__",array_merge($str,array($k)));
				$sqlvals[] = "'".e($v)."'";
        }
    }
} 

function packresulttoarray($resultline,$filter=array('q')) {
  $resasarray = array();
  foreach ($resultline as $key => $val) {
  	eval("\$resasarray['".str_replace("__","']['",$key)."']=\$val;"); //
  }
	$resasarrrayfiltered = array();
	foreach ($filter as $head) {
		$resasarrayfiltered[$head] = $resasarray[$head];
	}
	return $resasarrayfiltered;
}


function get_request_fields() {
	return 'HTTP_USER_AGENT, HTTP_REFERER, REMOTE_ADDR, QUERY_STRING';
}
function get_request_placeholders() {
	return "'%s', '%s', '%s', '%s'";
}
function get_request_data() {
	return array(
		e($_SERVER['HTTP_USER_AGENT']),
		e($_SERVER['HTTP_REFERER']),
		e($_SERVER['REMOTE_ADDR']),
		e($_SERVER['QUERY_STRING'])
	);
}



	function timeDiff($start, $end) {
		$start_ts = strtotime($start);
		$end_ts = strtotime($end);
		return $end_ts - $start_ts;
	}

	function timeSince($start) {
		$start_ts = strtotime($start);
		return time() - $start_ts;  // seconds
	}


